package com.nibianplus.volley.request;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;

import com.android.volley.AuthFailureError;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.nibianplus.util.AppUtil;
import com.nibianplus.util.ContextUtil;

import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

public class CommonFormRequest extends CommonPostRequest {
	private static final String BOUNDARY = "---------------------------7d931c5d043e";
	private static final String ENTRY_BOUNDARY = "--" + BOUNDARY;
	private static final String END_BOUNDARY = ENTRY_BOUNDARY + "--\r\n";

	private Map<String, File> files;

	public CommonFormRequest(String url, Map<String, Object> params, Map<String, File> files,
			Listener<JSONObject> listener, ErrorListener errorListener) {
		super(url, params, listener, errorListener);
		this.files = files;
	}

	@Override
	public Map<String, String> getHeaders() throws AuthFailureError {
		Map<String, String> headers = new HashMap<String, String>();
		SharedPreferences sp = ContextUtil.getContext().getSharedPreferences(AppUtil.getAppName(),
				Context.MODE_PRIVATE);
		String cookie = (String) sp.getString("cookie", "");
		if (!TextUtils.isEmpty(cookie)) {
			headers.put("Cookie", cookie);
		}
		//headers.put("Content-Type", "application/x-www-form-urlencoded");
		headers.put("enctype", "multipart/form-data");
		return headers;
	}

	@Override
	public byte[] getBody() throws AuthFailureError {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		try {

			Map<String, Object> params = getParams();
			if (params != null) {
				for (Map.Entry<String, Object> entry : params.entrySet()) {
					StringBuffer sb = new StringBuffer();
					sb.append(ENTRY_BOUNDARY);
					sb.append("\r\n");
					sb.append("Content-Disposition: form-data;name=\"");
					sb.append(entry.getKey());
					// sb.append("\"");
					// sb.append("\r\n\r\n");
					sb.append("\"\r\nContent-Type:");
					sb.append("text/plain;");
					sb.append("\r\n\r\n");
					sb.append(entry.getValue());
					sb.append("\r\n");
					bos.write(sb.toString().getBytes(getParamsEncoding()));
				}
			}

			if (files != null) {
				for (Map.Entry<String, File> entry : files.entrySet()) {
					StringBuffer sb = new StringBuffer();
					sb.append(ENTRY_BOUNDARY);
					sb.append("\r\n");
					sb.append("Content-Disposition: form-data;name=\"");
					sb.append(entry.getKey());
					sb.append("\";filename=\"" + entry.getValue().getName());
					sb.append("\"\r\nContent-Type:");
					sb.append("image/pjpeg;");
					sb.append("\r\n\r\n");
					bos.write(sb.toString().getBytes(getParamsEncoding()));

					InputStream is = new FileInputStream(entry.getValue());
					byte[] buffer = new byte[1024];
					int len = 0;
					while ((len = is.read(buffer)) != -1) {
						bos.write(buffer, 0, len);
					}

					is.close();

					bos.write("\r\n".getBytes(getParamsEncoding()));
				}
			}

			bos.write(END_BOUNDARY.getBytes(getParamsEncoding()));
		} catch (IOException e) {
			e.printStackTrace();
		}
		return bos.toByteArray();

	}

	@Override
	public String getBodyContentType() {
		return "multipart/form-data; boundary=" + BOUNDARY;
	}
}
